<?php

/**
 * +----------------------------------------------------------------------
 * | 插件初始化
 * +----------------------------------------------------------------------
 *                                            ...     .............
 *                                          ..   .:!o&*&&&&&ooooo&; .
 *                                        ..  .!*%*o!;.
 *                                      ..  !*%*!.      ...
 *                                     .  ;$$!.   .....
 *                          ........... .*#&   ...
 *                                     :$$: ...
 *                          .;;;;;;;:::#%      ...
 *                        . *@ooooo&&&#@***&&;.   .
 *                        . *@       .@%.::;&%$*!. . .
 *          ................!@;......$@:      :@@$.
 *                          .@!   ..!@&.:::::::*@@*.:..............
 *        . :!!!!!!!!!!ooooo&@$*%%%*#@&*&&&&&&&*@@$&&&oooooooooooo.
 *        . :!!!!!!!!;;!;;:::@#;::.;@*         *@@o
 *                           @$    &@!.....  .*@@&................
 *          ................:@* .  ##.     .o#@%;
 *                        . &@%..:;@$:;!o&*$#*;  ..
 *                        . ;@@#$$$@#**&o!;:   ..
 *                           :;:: !@;        ..
 *                               ;@*........
 *                       ....   !@* ..
 *                 ......    .!%$! ..     | AUTHOR: dfer
 *         ......        .;o*%*!  .       | EMAIL: df_business@qq.com
 *                .:;;o&***o;.   .        | QQ: 3504725309
 *        .;;!o&****&&o;:.    ..          | WEBSITE: http://www.dfer.site
 * +----------------------------------------------------------------------
 *
 */

namespace plugins\dfer_thinkcmf_tools;

use think\facade\Db;
use plugins\dfer_thinkcmf_tools\lib\Sms;
use plugins\dfer_thinkcmf_tools\model\OssUploadRecordModel;
use Dfer\Tools\Statics\Storage;

class DferThinkcmfToolsPlugin extends Plugin
{
    public $info = array(
        'name'        => 'DferThinkcmfTools',
        'title'       => 'dfer工具包',
        'description' => 'http://www.dfer.site',
        'status'      => 1,
        'author'      => 'df',
        'version'     => ''
    );

    //插件是否有后台管理界面
    public $hasAdmin = 1;

    public function __construct()
    {
        if (!class_exists('Dfer\Tools\Common')) {
            die("《{$this->info['title']}》缺少`dfer/tools`组件");
        }
        parent::__construct();
    }

    ////////////////////////////////////////////////// 钩子方法 START //////////////////////////////////////////////////
    // 常用的钩子	https://www.thinkcmf.com/docs/cmf8/#/%E5%90%8E%E5%8F%B0%E9%92%A9%E5%AD%90
    // 表名	cmf_hook

    /**
     * 模块初始化
     * 
     * $this->app->event->trigger('ModuleInit');
     */
    public function moduleInit()
    {
        // var_dump('moduleInit');
        // ********************** 静态缓存 START **********************
        if (config('html.status')) {
            $htmls = config('html.rules');
            Storage::readHtml($htmls, null, request()->controller(), request()->action());
        }
        // **********************  静态缓存 END  **********************
    }

    /**
     * 视图输出过滤
     * 
     * <hook name="view_filter"/>
     * 
     * $content=parent::fetch($template, $vars, $config);
     * hook('view_filter',$content);
     * 
     */
    public function viewFilter($content)
    {
        // var_dump('viewFilter');
        // ********************** 静态缓存 START **********************
        if (config('html.status')) {
            echo Storage::writeHtml($content);
        } else {
            echo $content;
        }
        // **********************  静态缓存 END  **********************
        die;
    }


    /**
     * 控制器开始
     * 
     * $this->app->event->trigger('ActionBegin');
     */
    public function actionBegin()
    {
        // var_dump('actionBegin');
        // echo 123;die;
    }

    /**
     * 前端页面初始化
     * <hook name="home_init"/>
     */
    public function homeInit()
    {
        // var_dump('homeInit');
        if (!isset($this->config['custom_home_status']) || $this->config['custom_home_status'] == 0): return;
        endif;

        if ($this->checkVersion(Constants::V8)) {
            return $this->view(__FUNCTION__);
        } else {
            // tc8以下的版本，插件页面也会触发前端钩子，需要过滤
            // var_dump(request()->action());
            if (request()->action()) {
                // 前端页面
                die($this->view(__FUNCTION__));
            }
        }
    }

    /**
     * 后台页面初始化
     * <hook name="admin_init"/>
     */
    public function adminInit($data)
    {
        // var_dump('adminInit',$data);
        if ($data) {
            // 插件内的页面
        } else {
            // 插件外的页面
        }
    }


    /**
     * 后台登录页面
     * <hook name="admin_login"/>
     */
    public function adminLogin()
    {
        if (!$this->config['custom_login_status'] ?? null): return;
        endif;
        return $this->view(__FUNCTION__);
    }

    /**
     * 资源管理列表界面
     * <hook name="user_admin_asset_index_view"/>
     */
    public function userAdminAssetIndexView()
    {
        if (!$this->config['custom_asset_status']): return;
        endif;

        $result = OssUploadRecordModel::field('a.*,u.user_login,u.user_email,u.user_nickname')
            ->alias('a')->join('user u', 'a.user_id = u.id')
            ->order('create_time', 'DESC')
            ->paginate(10);
        $this->assign('assets', $result->items());
        $this->assign('page', $result->render());

        return $this->view(__FUNCTION__);
    }

    /**
     * 渲染后留言区的 html，如留言框，留言列表
     * <hook name="guestbook"/>
     * @param {Object} $param
     */
    public function guestbook($param)
    {
        return $this->view(__FUNCTION__);
    }


    /**
     * 
     * <hook name="admin_dashboard"/>
     * @param {Object} $param
     */
    public function adminDashboard($param)
    {
        die($this->view(__FUNCTION__));
    }


    /**
     * 发送验证码
     * <hook name="send_mobile_verification_code"/>
     * @param {Object} $param
     */
    public function sendMobileVerificationCode($param)
    {
        
        define("APP_DEBUG_SMS",env('APP_DEBUG_SMS', 0));
        
        if(APP_DEBUG_SMS){
            // 验证码没有过期时间
        	cmf_verification_code_log($param['mobile'], $param['code'], 0);
        	$this->success("验证码：{$param['code']}");
        }
        
        $mobile        = $param['mobile']; //手机号
        $code          = $param['code']; //验证码
        $config        = $this->config;
        
        switch($config['sms_type']){
            case 2:
                // 短信宝
                $statusStr = array(
                    "0" => "短信发送成功",
                    "-1" => "参数不全",
                    "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
                    "30" => "密码错误",
                    "40" => "账号不存在",
                    "41" => "余额不足",
                    "42" => "帐户已过期",
                    "43" => "IP地址限制",
                    "50" => "内容含有敏感词"
                );
                $smsapi = "http://api.smsbao.com/";
                $user = $config['smsbao_user']; //短信平台帐号
                $pass = md5($config['smsbao_pwd']); //短信平台密码
                $content= '【'.$config['smsbao_sign'].'】'.str_replace('$code',$code,$config['smsbao_template_id']);//要发送的短信内容
                $phone = $mobile;//要发送短信的手机号码
                $sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);
                $result = file_get_contents($sendurl) ;
                if($result == '0'){//发送成功
                    $result = [
                        'error'=>0,
                        'message'=>$statusStr[$result]
                    ];
                }else{
                    $result = [
                        'error'=>-1,
                        'message'=>$statusStr[$result]
                    ];
                }                
                break;
            case 1:
                // 阿里云
                $expire_minute = intval($config['ali_expire_minute']);
                $expire_minute = empty($expire_minute) ? 30 : $expire_minute;
                $expire_time   = time() + $expire_minute * 60;
                $result        = false;
                //send message
                if ($code !== false) {
                    $params['PhoneNumbers'] = $mobile;
                    $params['SignName'] = $config['ali_sign_name'];
                    $params['TemplateCode'] = $config['ali_template_code'];
                    $params['TemplateParam'] = array(
                        $config['ali_code_key'] => "{$code}"
                    );
                    $sms = new Sms($config['ali_access_key_id'], $config['ali_access_key_secret']);
                    $reponse = $sms->sendSms($params);
                    // var_dump($config,$params,$sms->getError());
                    if ($reponse) {
                        $result = array(
                            'error' => 0,
                            'message' => '发送成功！'
                        );
                    } else {
                        $result = array(
                            'error' => 1,
                            'message' => $sms->getError()
                        );
                    }
                } else {
                    $result = array(
                        'error' => 1,
                        'message' => '发送次数过多，不能再发送'
                    );
                }
                break;
            default:
                break;
        }
        
        return $result;
    }



    //////////////////////////////////////////////////  钩子方法 END  //////////////////////////////////////////////////

    ////////////////////////////////////////////////// 自定义方法 START //////////////////////////////////////////////////
    /**
     * 创建表
     * @param {Object} $var 变量
     **/
    public function createTable($var = null)
    {
        $prefix = $this->getPrefix();
        $sql[] = <<<sql
CREATE TABLE IF NOT EXISTS `{$prefix}oss_upload_record`  (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` int(11) UNSIGNED NOT NULL DEFAULT 0,
`file_path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '',
`url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '',
`create_time` int(11) UNSIGNED NULL DEFAULT 0,
`type` tinyint(1) UNSIGNED NULL DEFAULT 1 COMMENT '分类 1 图片 2 视频',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic COMMENT = 'oss上传记录' ;	
sql;

        $sql[] = <<<sql
CREATE TABLE IF NOT EXISTS `{$prefix}guestbook`  (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '留言人姓名',
`email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '留言人邮箱',
`phone` char(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '手机号码',
`msg` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '留言内容',
`create_time` int(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT '创建时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic COMMENT = '留言';
sql;

        $sql[] = <<<sql
CREATE TABLE IF NOT EXISTS `{$prefix}bt_site`  (
`site_id` int(11) NOT NULL DEFAULT '0' COMMENT '站点id',
`site_path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '站点目录',
`run_path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '站点运行目录',
`maintenance_logo` longtext NOT NULL COMMENT '维护页面logo',
`maintenance_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '维护截止时间',
`site_status` tinyint(3) unsigned NOT NULL DEFAULT '1' COMMENT '状态。0：正常；100：维护',
`create_time` int(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT '创建时间',
`update_time` int(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT '更新时间',
PRIMARY KEY (`site_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic COMMENT = 'bt站点配置';
sql;

        foreach ($sql as $key => $value) {
            $res[] = Db::query($value);
        }

        return true;
    }

    /**
     * 删除表
     * @param {Object} $var 变量
     **/
    public function dropTable($var = null)
    {
        $prefix = $this->getPrefix();

        $sql[]  = <<<sql
        DROP TABLE IF EXISTS `{$prefix}oss_upload_record`;
        sql;

        $sql[] = <<<sql
        DROP TABLE IF EXISTS `{$prefix}guestbook`;
        sql;

        $sql[] = <<<sql
        DROP TABLE IF EXISTS `{$prefix}bt_site`;
        sql;

        foreach ($sql as $key => $value) {
            $res[] = Db::query($value);
        }

        return true;
    }


    /**
     * 获取表前缀
     * @param object $var 变量
     * @return mixed
     **/
    public function getPrefix($var = null)
    {
        if ($this->checkVersion()) {
            $prefix = config('database.connections.mysql.prefix');
        } else {
            $prefix = config('database.prefix');
        }
        $prefix = sprintf("{$prefix}plugin_%s_", cmf_parse_name($this->info['name']));
        return $prefix;
    }


    //////////////////////////////////////////////////  自定义方法 END  //////////////////////////////////////////////////
}
